import { NextRequest, NextResponse } from 'next/server';
import { DocumentOperations } from '@/lib/database-operations';
import { documentProcessor } from '@/lib/vectorization';
import { unlink } from 'fs/promises';
import { existsSync } from 'fs';

// 获取单个文档
export async function GET(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const document = await DocumentOperations.getById(id);

    if (!document) {
      return NextResponse.json(
        { success: false, error: '文档不存在' },
        { status: 404 }
      );
    }

    return NextResponse.json({
      success: true,
      data: document,
    });
  } catch (error) {
    console.error('获取文档失败:', error);
    return NextResponse.json(
      { success: false, error: '获取文档失败' },
      { status: 500 }
    );
  }
}

// 删除文档
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    // 获取文档信息
    const document = await DocumentOperations.getById(id);

    if (!document) {
      return NextResponse.json(
        { success: false, error: '文档不存在' },
        { status: 404 }
      );
    }

    // 删除向量数据
    await documentProcessor.deleteDocumentVectors(id);

    // 删除文件
    if (document.file_path && existsSync(document.file_path)) {
      try {
        await unlink(document.file_path);
      } catch (error) {
        console.warn('删除文件失败:', error);
      }
    }

    // 删除数据库记录
    const deleted = await DocumentOperations.delete(id);

    if (!deleted) {
      return NextResponse.json(
        { success: false, error: '删除文档失败' },
        { status: 500 }
      );
    }

    return NextResponse.json({
      success: true,
      message: '文档删除成功',
    });
  } catch (error) {
    console.error('删除文档失败:', error);
    return NextResponse.json(
      { success: false, error: '删除文档失败' },
      { status: 500 }
    );
  }
}

// 重新处理文档
export async function PUT(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  try {
    const { id } = await params;
    const { action } = await request.json();

    if (action === 'reprocess') {
      // 重新处理文档
      const success = await documentProcessor.reprocessDocument(id);

      if (!success) {
        return NextResponse.json(
          { success: false, error: '重新处理文档失败' },
          { status: 500 }
        );
      }

      return NextResponse.json({
        success: true,
        message: '文档重新处理成功',
      });
    }

    return NextResponse.json(
      { success: false, error: '不支持的操作' },
      { status: 400 }
    );
  } catch (error) {
    console.error('处理文档操作失败:', error);
    return NextResponse.json(
      { success: false, error: '处理文档操作失败' },
      { status: 500 }
    );
  }
}
